import mysql.connector
import copy
from impl.perf_stat.function_call import record_running_time


class DatabaseConnection:
    def __init__(self, connection_config: dict, buffered=False):
        self.connection_config = copy.copy(connection_config)
        self.buffered = buffered
        self.table_names = self.connection_config["table_names"]
        del self.connection_config["table_names"]

    @record_running_time
    def __enter__(self):
        self.ctx = mysql.connector.connect(**self.connection_config)
        self.cursor = self.ctx.cursor(self.buffered)

    @record_running_time
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.ctx.close()

    @record_running_time
    def commit(self):
        self.ctx.commit()

    @record_running_time
    def rollback(self):
        self.ctx.rollback()
